/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package LinkRetriever;

import DBSupport.DBApi;
import DataStructures.Project;
import General.Utilities;
import java.util.ArrayList;

/**
 *
 * @author Manuel
 */
public class DataManager {

    private ArrayList<String> links;
    private ArrayList<Project> projects;
    private DBApi api;
    private static int linkCounter;

    public DataManager(DBApi a){
        linkCounter = 0;
        api = a;
        links = new ArrayList<String>();
        projects = new ArrayList<Project>();
    }

    public void addNewProject(Project p){
        projects.add(p);
    }

    public synchronized Project processNextProject(){
        Project current = projects.get(0);
        projects.remove(0);
        return current;
    }

    public void addNewLink(String link,int pos){
        //TODO choose alternating requests
            links.add(pos,link);

    }

    //returns one time a google code and the next time a sourceforge link
    public synchronized String processNextLink(){
        linkCounter++;
        System.out.println(this.getLinksLeft()+" projects to go...");
        if(links.size()>0){
            String nextLink = "";
            //alternate such that one link at the first and one link at the last position of the list is taken
            if(this.getLinksLeft() %2 == 0){
                nextLink = links.get(0);
                links.remove(0);
            }

            else if(this.getLinksLeft() % 2 == 1)
            {
                nextLink = links.get(links.size()-1);
                links.remove(links.size()-1);
            }
            return nextLink;
        }
        return null;
    }

    public int getLinksLeft(){
        return links.size();
    }

    public int getLinksLeft(String forge){
        int counter=0;
        for(int i = 0;i<links.size();i++){
            if(links.get(i).contains(forge))
                counter++;
        }
        return counter;
    }

    public int getProjectsLeft() {
        return projects.size();
    }

    public void parseProjectLinks(String[] fileNames){
        int fileNo = fileNames.length;
        String currentFile;
        String content="";

        links = api.getAllInterestingLinks();
    }

    private void gatherLinks(String content, int offset){
        //first eliminate the date
        int indexOfLim = content.indexOf(";");
        String currentLink;
        int counter = -1;
        //now extract every link and add it into the datamanager
        while(indexOfLim != -1){
            currentLink = content.substring(0, indexOfLim);
            this.addNewLink(currentLink,counter + offset);
            content = content.substring(indexOfLim+1);
            indexOfLim = content.indexOf(";");
            counter+=offset;
        }
    }


}
